package icu.d4peng.basic.knife4j.extension;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.customizers.GlobalOperationCustomizer;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.github.xiaoymin.knife4j.core.conf.ExtensionsConstants;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.github.xiaoymin.knife4j.extend.util.ExtensionUtils;

import io.swagger.v3.oas.models.Operation;

/**
 * @author d4peng d4peng@qq.com
 * @date 2023-11-25 19:42:44
 */
public class Knife4jOperationCustomizer implements GlobalOperationCustomizer {

	private static final Logger LOGGER = LoggerFactory.getLogger(Knife4jOperationCustomizer.class);

	@Override
	public Operation customize(Operation operation, HandlerMethod handlerMethod) {
		ApiOperationSupport operationSupport = AnnotationUtils.findAnnotation(handlerMethod.getMethod(),
				ApiOperationSupport.class);
		if (operationSupport != null) {
			String author = ExtensionUtils.getAuthors(operationSupport);
			if (StrUtil.isNotBlank(author)) {
				operation.addExtension(ExtensionsConstants.EXTENSION_AUTHOR, author);
			}
			if (operationSupport.order() != 0) {
				operation.addExtension(ExtensionsConstants.EXTENSION_ORDER, operationSupport.order());
			}
		}
		else {
			// 如果方法级别不存在，再找一次class级别的
			ApiSupport apiSupport = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), ApiSupport.class);
			if (apiSupport != null) {
				String author = ExtensionUtils.getAuthor(apiSupport);
				if (StrUtil.isNotBlank(author)) {
					operation.addExtension(ExtensionsConstants.EXTENSION_AUTHOR, author);
				}
				if (apiSupport.order() != 0) {
					operation.addExtension(ExtensionsConstants.EXTENSION_ORDER, apiSupport.order());
				}
			}
		}
		return operation;
	}

}
